// Copyright  2004-2008 Backplane Ltd.
//
// This file is part of Ubiquity formsPlayer
//
// Ubiquity formsPlayer is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
//
// Ubiquity formsPlayer is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License
// along with Ubiquity formsPlayer If not, see <http://www.gnu.org/licenses/>.
//	
//
//   Purpose: Implementation of CXFormsInstanceCollection.
//   $Id$
#include "stdafx.h"
#include "InstanceCollection.h"

CXFormsInstanceCollection::CXFormsInstanceCollection()
{
}

CXFormsInstanceCollection::~CXFormsInstanceCollection()
{
}

STDMETHODIMP CXFormsInstanceCollection::get_length(long* pVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	if(pVal) {
		*pVal = m_Collection.size();
		return S_OK;
	}

	return E_POINTER;
}

STDMETHODIMP CXFormsInstanceCollection::GetItem(long nIndex, IXMLDOMDocument **ppInstance)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	if(ppInstance) {
		if(nIndex >= 0 && nIndex < m_Collection.size()) {
			int nCount = 0;
			for(instancemap_t::iterator i = m_Collection.begin(); i != m_Collection.end(); ++i) {
				if(nCount++ == nIndex) {
					*ppInstance = i->second;
					if(*ppInstance) {
						(*ppInstance)->AddRef();
						return S_OK;
					}
				}
			}
		}

		return E_INVALIDARG;
	}

	return E_POINTER;
}

STDMETHODIMP CXFormsInstanceCollection::GetItemById(BSTR sId, IXMLDOMDocument **ppInstance)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	if(ppInstance) {
		instancemap_t::iterator pItem;
		if(sId && wcslen(sId) > 0)
			pItem = m_Collection.find(sId);
		else
			pItem = m_Collection.begin();

		if(pItem != m_Collection.end()) {
			*ppInstance = pItem->second;
			if(*ppInstance) {
				(*ppInstance)->AddRef();
				return S_OK;
			}
		}

		return E_INVALIDARG;
	}

	return E_POINTER;
}

HRESULT CXFormsInstanceCollection::FinalConstruct()
{
	return S_OK;
}

void CXFormsInstanceCollection::FinalRelease()
{
}

void CXFormsInstanceCollection::AddInstance(BSTR sId, IXMLDOMDocument *pInstance)
{
	if(pInstance)
		m_Collection.insert(--m_Collection.end(), instancemapentry_t(sId, pInstance));
}
